//
//  KDWebSetController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/3.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDWebSetController.h"
#import "KDWebSetCellModel.h"
#import "KDWebAddCell.h"
#import "KDMonitorRequestTool.h"
#import "WebsiteMonitorGetParam.h"
#import "WebsiteMonitorGetResult.h"
#import "KDMWebAddParam.h"
#import "KDMWebAddResult.h"
#import "KDWebsiteModel.h"
#import "SVProgressHUD.h"
#import "WebsiteAddParam.h"
#import "KDAddWebsiteResultModel.h"
#import "KDHttpTool.h"
#import "KDDropdownMenu.h"
#import "KDTitleMenuController.h"
#define CELL_HEIGHT 40
@interface KDWebSetController ()<UITableViewDelegate, UITableViewDataSource, KDWebAddCellDelegate,UITextFieldDelegate, KDDropdownMenuDelegate,KDTitleMenuControllerDelegate>
@property (nonatomic, strong) NSArray *infoArr;
@property (nonatomic, weak) UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *printView;
/**
 *  从注释到输入View的高度距离
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *noticeToPrintVIew_Constraint_Height;
@property (weak, nonatomic) IBOutlet UITextField *printTf;
@property (nonatomic, strong) NSArray *websiteArr;

@property (nonatomic, weak) KDDropdownMenu *menu;
@end

@implementation KDWebSetController
- (NSArray *)websiteArr{
    if (!_websiteArr) {
        _websiteArr = [NSArray array];
        
    }
    return _websiteArr;
}
- (NSArray *)infoArr{
    if (!_infoArr) {
        _infoArr = [NSArray array];
    }
    return _infoArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackGroundColor;
    self.title = @"网站监测设置";
//    [self setUpBackItm];
    [self setUpNavBar];
    [self setUpTableView];
    self.printTf.delegate = self;
    //添加手势
    UITapGestureRecognizer *hide = [[UITapGestureRecognizer alloc] init];
    [hide addTarget:self action:@selector(hideTheKeyBoard)];
    [self.view addGestureRecognizer:hide];
}
- (void)setUpNavBar{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backViewClick)];
}
- (void)setUpTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , CGRectGetMaxY(self.printView.frame), screenW,  self.infoArr.count * CELL_HEIGHT) style:UITableViewStylePlain];
    self.noticeToPrintVIew_Constraint_Height.constant = CGRectGetMaxY(tableView.frame) - self.printView.height +10;
    KDLog(@"%@", NSStringFromCGRect(self.tableView.frame));
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.separatorColor = [UIColor whiteColor];
    [self.view addSubview:tableView];
    
}

#pragma mark - 事件点击区
/**
 *  返回按钮被点击了
 */
- (void)backViewClick{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  获取网站按钮被点击了
 */
- (IBAction)getWebUrlBtnClick:(UIButton *)sender {
    [self getWebUrlRequest];
    
}
- (IBAction)saveBtnClick:(UIButton *)sender {
    NSMutableArray *tempArr = [NSMutableArray array];
    for (KDWebSetCellModel *model in self.infoArr) {
        if (model.add) {
            KDWebsiteModel *websiteModel = [[KDWebsiteModel alloc]init];
            websiteModel.share = model.share;
            websiteModel.name = model.websiteName;
            websiteModel.wsm_id = model.ID;
            websiteModel.url = model.desc;
            NSDictionary *dic = [websiteModel keyValues];
            [tempArr addObject:dic];
        }
        
    }
    self.websiteArr = tempArr;
    [self addWebUrlRequest];
    
}

#pragma mark - 网络请求区
/**
 *  获取输入网址所属网站
 */
- (void)getWebUrlRequest{
    WebsiteMonitorGetParam *param = [[WebsiteMonitorGetParam alloc]init];
    param.url = self.printTf.text;
    param.method = @"getMonitorWebSiteUrlInfo";
    [SVProgressHUD showWithStatus:@"正在抓取网站！" maskType:SVProgressHUDMaskTypeGradient ];
    [KDMonitorRequestTool websiteMonitorGetWithParam:param success:^(WebsiteMonitorGetResult *responseObejct) {//请求成功状态
        [SVProgressHUD dismiss];
        if ([responseObejct.status isEqualToString:@"ok"]) {
            if (responseObejct.info.count == 0) {//如果没有数据，就告诉他没有
                [SVProgressHUD showInfoWithStatus:@"没有相关网站！" maskType:SVProgressHUDMaskTypeBlack];
            }else{
                self.infoArr = responseObejct.info;
                CGFloat height = CELL_HEIGHT * self.infoArr.count + CGRectGetMaxY(self.printView.frame);
                if (200 <= screenH - height) {
                    self.tableView.height  = CELL_HEIGHT * self.infoArr.count;
                }else{
                    self.tableView.height = CELL_HEIGHT * 8;
                }
                self.tableView.contentSize = CGSizeMake(screenW, CELL_HEIGHT * self.infoArr.count + 64);
                self.noticeToPrintVIew_Constraint_Height.constant = CGRectGetMaxY(self.tableView.frame) - self.printView.height +10;
                [self.tableView reloadData];
            }
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"抓取主题失败!" maskType:SVProgressHUDMaskTypeGradient];
        KDLog(@"%@", error);
    }];
}
/**
 *  添加网站的请求
 */
- (void)addWebUrlRequest{
    WebsiteAddParam *param = [[WebsiteAddParam alloc]init];
    param.method = @"addMonitorWebSiteBatch";
    if (!self.websiteArr.count) {
        [SVProgressHUD showErrorWithStatus:@"尚未选中网站！" maskType:SVProgressHUDMaskTypeGradient ];
        return;
    }
    NSString *arrStr = [self.websiteArr JSONString];
    param.webSiteArray= arrStr;
    [SVProgressHUD showWithStatus:@"正在添加！" maskType:SVProgressHUDMaskTypeGradient ];

    [KDMonitorRequestTool addWebMonitorWithParam:param success:^(KDMWebAddResult *responseObejct) {//请求成功状态
        [SVProgressHUD dismiss];
        if ([responseObejct.status isEqualToString:@"ok"]) {
//            for (KDAddWebsiteResultModel *model in responseObejct.info) {
//                KDLog(@"%@", model.name);
//            }
            
            // 1.创建下拉菜单
            KDDropdownMenu *menu = [KDDropdownMenu menu];
            menu.delegate = self;
            self.menu = menu;
            // 2.设置内容
            KDTitleMenuController *vc = [[KDTitleMenuController alloc] init];
            vc.delegate = self;
            vc.info = responseObejct.info;
            vc.view.height = 300;
            vc.view.width = screenW - 30;
            vc.newSize = vc.view.size;
            menu.contentController = vc;
            // 3.显示
            [menu showFrom:self.printView];

        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"添加主题失败!" maskType:SVProgressHUDMaskTypeGradient];
        KDLog(@"%@", error);
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KDWebAddCell *cell = [KDWebAddCell cellWithTableView:tableView];
    cell.model = self.infoArr[indexPath.row];
    cell.delegate = self;
    return cell;
}
- (CGFloat) tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELL_HEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELL_HEIGHT;
}
#pragma mark - KDWebAddCellDelegate
/**
 *  添加监测按钮被点击了
 *
 *  @param model 
 */
- (void)KDWebAddCell:(KDWebAddCell *)cell addBtnClickWithModel:(KDWebSetCellModel *)model{
    [self repalceInfoWithCell:cell];
    
}
- (void)KDWebAddCell:(KDWebAddCell *)cell shareBtnClickWithModel:(KDWebSetCellModel *)model{
    [self repalceInfoWithCell:cell];
}

- (void)repalceInfoWithCell:(KDWebAddCell*)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.infoArr];
    [tempArr replaceObjectAtIndex:indexPath.row withObject:cell.model];
    self.infoArr = tempArr;
}
#pragma mark - 隐藏键盘
- (void)hideTheKeyBoard
{
    [self.view endEditing:YES];
}
#pragma mark -UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.printTf resignFirstResponder];
    return YES;
}

#pragma mark - KDDropdownMenuDelegate

#pragma mark - KDTitleMenuControllerDelegate
- (void)confirmBtnClick{
    [self.menu dismiss];
}
@end
